package com.ghxxzx.dagl.utils;

import com.ghxxzx.dagl.entity.Clxx;
import com.ghxxzx.dagl.entity.Daxx;
import com.ghxxzx.dagl.entity.DaxxWs;
import com.ghxxzx.dagl.entity.GryfKj;
import com.ghxxzx.dagl.vo.*;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.analysis.core.StopAnalyzer;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.ngram.NGramTokenFilter;
import org.apache.lucene.analysis.ngram.NGramTokenizer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Version;
import org.apache.tools.ant.filters.SortFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: 刘华
 * @Date: 2020/11/25 10:46
 * @Version 1.0
 */
@Service
public class LuceneUtiles {

    @Value("${lucene.index}")
    private String indexPath;


    public Integer searchDaxxWsOuter(Integer typeId, String keyword, Integer startyear, Integer stopyear) throws org.apache.lucene.queryparser.classic.ParseException {
        BooleanQuery booleanQuery = new BooleanQuery();
        //模糊参数
        List<String> list = getWsCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }


        //全等查询
        TermQuery termQuery = new TermQuery(new Term("wstypeId", typeId + ""));
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("wsnf", startyear, stopyear, true, true);
        if (startyear != null && stopyear != null) {
            BytesRef min = new BytesRef((startyear + "").getBytes());
            BytesRef max = new BytesRef((stopyear + "").getBytes());
            TermRangeQuery year = new TermRangeQuery("wsnf", min, max, true, true);
            booleanQuery.add(year, BooleanClause.Occur.MUST);
            booleanQuery.add(year, BooleanClause.Occur.MUST);
        }

        // 多条件必备神器
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);


        int hits = 0;
        Directory d=null;
        DirectoryReader open=null;
        try {
             d = FSDirectory.open(new File(indexPath));
             open = DirectoryReader.open(d);

            //2、使用IndexSearcher进行查询索引表
            //建立IndexSearcher对象,参数为索引表目录
            IndexSearcher indexSearcher = new IndexSearcher(open);

//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
            TopDocs topDocs = indexSearcher.search(booleanQuery, 1);
            System.out.println("总共有【" + topDocs.totalHits + "】条匹配的结果。");
            hits = topDocs.totalHits;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return hits;
    }

    public Integer searchDaxxOuter(Integer typeId, String keyword, Integer startyear, Integer stopyear) throws org.apache.lucene.queryparser.classic.ParseException {
        BooleanQuery booleanQuery = new BooleanQuery();
        //模糊参数
        List<String> list = getKjCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }


        //全等查询
        TermQuery termQuery = new TermQuery(new Term("kjtypeId", typeId + ""));
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("kjyear", startyear, stopyear, true, true);

        if (startyear != null && stopyear != null) {
            BytesRef min = new BytesRef((startyear + "").getBytes());
            BytesRef max = new BytesRef((stopyear + "").getBytes());
            TermRangeQuery year = new TermRangeQuery("kjyear", min, max, true, true);
            booleanQuery.add(year, BooleanClause.Occur.MUST);
            booleanQuery.add(year, BooleanClause.Occur.MUST);
        }
//        BytesRef min = new BytesRef((startyear + "").getBytes());
//        BytesRef max = new BytesRef((stopyear + "").getBytes());
//        TermRangeQuery year = new TermRangeQuery("kjyear", min, max, true, true);
        // 多条件必备神器


        int hits = 0;
        Directory d=null;
        DirectoryReader open=null;
        try {
            d = FSDirectory.open(new File(indexPath));
            open = DirectoryReader.open(d);
            //2、使用IndexSearcher进行查询索引表
            //建立IndexSearcher对象,参数为索引表目录
            IndexSearcher indexSearcher = new IndexSearcher(open);

//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
            TopDocs topDocs = indexSearcher.search(booleanQuery, 1);

            System.out.println("总共有【" + topDocs.totalHits + "】条匹配的结果。");
            hits = topDocs.totalHits;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return hits;
    }

    public Integer searchGryfOuter(Integer typeId, String keyword, Integer startyear, Integer stopyear) throws org.apache.lucene.queryparser.classic.ParseException {
        BooleanQuery booleanQuery = new BooleanQuery();
        //模糊参数
        List<String> list = getGryfCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }


        //全等查询
        TermQuery termQuery = new TermQuery(new Term("grtypeId", typeId + ""));
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("gryear", startyear, stopyear, true, true);
        if (startyear != null && stopyear != null) {
            BytesRef min = new BytesRef((startyear + "").getBytes());
            BytesRef max = new BytesRef((stopyear + "").getBytes());
            TermRangeQuery year = new TermRangeQuery("gryear", min, max, true, true);
            booleanQuery.add(year, BooleanClause.Occur.MUST);
            booleanQuery.add(year, BooleanClause.Occur.MUST);
        }

        // 多条件必备神器

        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);


        int hits = 0;
        Directory d=null;
        DirectoryReader open=null;
        try {
            d = FSDirectory.open(new File(indexPath));
            open = DirectoryReader.open(d);

            //2、使用IndexSearcher进行查询索引表
            //建立IndexSearcher对象,参数为索引表目录
            IndexSearcher indexSearcher = new IndexSearcher(open);

//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
            TopDocs topDocs = indexSearcher.search(booleanQuery, 1);
            System.out.println("总共有【" + topDocs.totalHits + "】条匹配的结果。");
            hits = topDocs.totalHits;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return hits;
    }

    public void searchDaxxPage(Integer typeId, String keyword, Integer startyear, Integer stopyear, PageQuery pageQuery, String sort, PageResult pageResult) throws org.apache.lucene.queryparser.classic.ParseException {

        //模糊参数
        List<String> list = getKjCondition();
        String[] fields = list.toArray(new String[list.size()]);

        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        BooleanQuery booleanQuery = new BooleanQuery();
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }


        //全等查询
        TermQuery termQuery = new TermQuery(new Term("kjtypeId", typeId + ""));
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("kjyear", startyear, stopyear, true, true);
        if (startyear != null && stopyear != null) {
            BytesRef min = new BytesRef((startyear + "").getBytes());
            BytesRef max = new BytesRef((stopyear + "").getBytes());
            TermRangeQuery year = new TermRangeQuery("kjyear", min, max, true, true);
            booleanQuery.add(year, BooleanClause.Occur.MUST);
        }

        // 多条件必备神器




//        设置排序 SortField 1排序字段 2字段类型 3true 降序 false升序
        SortField field = null;
        if (sort.equalsIgnoreCase("desc")) {
            field = new SortField("kjid", SortField.Type.INT, true);
        } else {
            field = new SortField("kjid", SortField.Type.INT, false);
        }

        Sort sortt = new Sort();
        sortt.setSort(field);

        Directory d=null;
        DirectoryReader open=null;
        try {
            d = FSDirectory.open(new File(indexPath));
            open = DirectoryReader.open(d);
            IndexSearcher indexSearcher = new IndexSearcher(open);
            ScoreDoc lastSd = getLastScoreDoc(pageQuery.getPageNum(), pageQuery.getPageSize(), booleanQuery, indexSearcher, sortt);
            //通过最后一个元素搜索下一页的pageSize元素
            TopDocs result = indexSearcher.searchAfter(lastSd, booleanQuery, pageQuery.getPageSize(), sortt);

//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
//        TopDocs topDocs = indexSearcher.search(booleanQuery, 0);
            System.out.println("总共有【" + result.totalHits + "】条匹配的结果。");
            int hits = result.totalHits;
            pageResult.setTotal(hits);
            ArrayList<Daxx> daxxes = new ArrayList<>();
            for (ScoreDoc scoreDoc : result.scoreDocs) {
                int doc = scoreDoc.doc;
                Daxx daxx = new Daxx();
                Document document = indexSearcher.doc(doc);
                setEntity(document, daxx);
                daxxes.add(daxx);
            }
            ArrayList<DajsKjVo> dajsKjVos = new ArrayList<>();
            for (Daxx daxx : daxxes) {
                dajsKjVos.add(new DajsKjVo(daxx.getId(), daxx.getId() + "", daxx.getDabh(), daxx.getXmmc(), daxx.getYear() + "", daxx.getDtslbh(), daxx.getJsdw(), daxx.getTypeId(), daxx.getTypeName()));
            }
            pageResult.setData(dajsKjVos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void searchDaxxWsPage(Integer typeId, String keyword, Integer startyear, Integer stopyear, PageQuery pageQuery, String sort, PageResult pageResult) throws org.apache.lucene.queryparser.classic.ParseException {

        //模糊参数
        List<String> list = getWsCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        BooleanQuery booleanQuery = new BooleanQuery();
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }
        //全等查询
        TermQuery termQuery = new TermQuery(new Term("wstypeId", typeId + ""));
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("wsyear", startyear, stopyear, true, true);
        // 多条件必备神器
        if (startyear != null && stopyear != null) {
            BytesRef min = new BytesRef((startyear + "").getBytes());
            BytesRef max = new BytesRef((stopyear + "").getBytes());
            TermRangeQuery year = new TermRangeQuery("wsnf", min, max, true, true);
            booleanQuery.add(year, BooleanClause.Occur.MUST);
        }

//        设置排序 SortField 1排序字段 2字段类型 3true 降序 false升序
        SortField field = null;
        if (sort.equalsIgnoreCase("desc")) {
            field = new SortField("wsid", SortField.Type.INT, true);
        } else {
            field = new SortField("wsid", SortField.Type.INT, false);
        }

        Sort sortt = new Sort();
        sortt.setSort(field);

        Directory d=null;
        DirectoryReader open=null;
        try {
            d = FSDirectory.open(new File(indexPath));
            open = DirectoryReader.open(d);


            IndexSearcher indexSearcher = new IndexSearcher(open);
            ScoreDoc lastSd = getLastScoreDoc(pageQuery.getPageNum(), pageQuery.getPageSize(), booleanQuery, indexSearcher, sortt);
            //通过最后一个元素搜索下一页的pageSize元素
            TopDocs result = indexSearcher.searchAfter(lastSd, booleanQuery, pageQuery.getPageSize(), sortt);

//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
//        TopDocs topDocs = indexSearcher.search(booleanQuery, 0);
            System.out.println("总共有【" + result.totalHits + "】条匹配的结果。");
            int hits = result.totalHits;
            pageResult.setTotal(hits);
            ArrayList<DaxxWs> daxxWsList = new ArrayList<>();
            for (ScoreDoc scoreDoc : result.scoreDocs) {
                int doc = scoreDoc.doc;
                DaxxWs daxxWs = new DaxxWs();
                Document document = indexSearcher.doc(doc);
                setEntity(document, daxxWs);
                daxxWsList.add(daxxWs);
            }
            ArrayList<DajsWsVo> dajsWsVos = new ArrayList<>();
            for (DaxxWs daxxWs : daxxWsList) {
                dajsWsVos.add(new DajsWsVo(daxxWs.getId(), daxxWs.getId() + "", daxxWs.getDabh(), daxxWs.getWjmc(), daxxWs.getWh(), daxxWs.getDwmc(), daxxWs.getTypeId(), daxxWs.getTypeName(), daxxWs.getNf() + ""));
            }
            pageResult.setData(dajsWsVos);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void searchDaxxPageMl(Integer typeId, String keyword, Integer startyear, Integer stopyear, PageQuery pageQuery, String sort, PageResult pageResult, String year) throws org.apache.lucene.queryparser.classic.ParseException {

        //模糊参数
        List<String> list = getKjCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        BooleanQuery booleanQuery = new BooleanQuery();
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }


        //全等查询
        TermQuery termQuery = new TermQuery(new Term("kjtypeId", typeId + ""));
        TermQuery termQuery2 = new TermQuery(new Term("kjyear", year + ""));
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等


//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("kjyear", startyear, stopyear, true, true);
//
//        BytesRef min = new BytesRef((startyear+"").getBytes());
//        BytesRef max = new BytesRef((stopyear+"").getBytes());
//        TermRangeQuery year = new TermRangeQuery("kjyear", min, max, true, true);
        // 多条件必备神器

        booleanQuery.add(termQuery2, BooleanClause.Occur.MUST);
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);


//        设置排序 SortField 1排序字段 2字段类型 3true 降序 false升序
        SortField field = null;
        if (sort.equalsIgnoreCase("desc")) {
            field = new SortField("kjid", SortField.Type.INT, true);
        } else {
            field = new SortField("kjid", SortField.Type.INT, false);
        }

        Sort sortt = new Sort();
        sortt.setSort(field);
        Directory d=null;
        DirectoryReader open=null;
        try {
             d = FSDirectory.open(new File(indexPath));
             open = DirectoryReader.open(d);


            IndexSearcher indexSearcher = new IndexSearcher(open);
            ScoreDoc lastSd = getLastScoreDoc(pageQuery.getPageNum(), pageQuery.getPageSize(), booleanQuery, indexSearcher, sortt);
            //通过最后一个元素搜索下一页的pageSize元素
            TopDocs result = indexSearcher.searchAfter(lastSd, booleanQuery, pageQuery.getPageSize(), sortt);

//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
//        TopDocs topDocs = indexSearcher.search(booleanQuery, 0);
            System.out.println("总共有【" + result.totalHits + "】条匹配的结果。");
            int hits = result.totalHits;
            pageResult.setTotal(hits);
            ArrayList<Daxx> daxxes = new ArrayList<>();
            for (ScoreDoc scoreDoc : result.scoreDocs) {
                int doc = scoreDoc.doc;
                Daxx daxx = new Daxx();
                Document document = indexSearcher.doc(doc);
                setEntity(document, daxx);
                daxxes.add(daxx);
            }
            ArrayList<DamlKjVo> damlKjVos = new ArrayList<>();
            for (Daxx record : daxxes) {
                damlKjVos.add(new DamlKjVo(record.getId(), record.getId() + "", record.getDabh(), record.getXmmc(), record.getYear() + "", record.getDtslbh(), record.getJsdw(), record.getJswz(), record.getJsgcsgxkzbh(), record.getDaccwz()));
            }
            pageResult.setData(damlKjVos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void searchDaxxWsPageMl(Integer typeId, String keyword, Integer startyear, Integer stopyear, PageQuery pageQuery, String sort, PageResult pageResult, String year) throws org.apache.lucene.queryparser.classic.ParseException {

        //模糊参数
        List<String> list = getWsCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        BooleanQuery booleanQuery = new BooleanQuery();
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }
        //全等查询
        TermQuery termQuery = new TermQuery(new Term("wstypeId", typeId + ""));
        TermQuery termQuery2 = new TermQuery(new Term("wsnf", year + ""));
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("wsyear", startyear, stopyear, true, true);
//        BytesRef min = new BytesRef((startyear+"").getBytes());
//        BytesRef max = new BytesRef((stopyear+"").getBytes());
//        TermRangeQuery year = new TermRangeQuery("wsnf", min, max, true, true);
        // 多条件必备神器
        booleanQuery.add(termQuery2, BooleanClause.Occur.MUST);
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);

//        设置排序 SortField 1排序字段 2字段类型 3true 降序 false升序
        SortField field = null;
        if (sort.equalsIgnoreCase("desc")) {
            field = new SortField("wsid", SortField.Type.INT, true);
        } else {
            field = new SortField("wsid", SortField.Type.INT, false);
        }

        Sort sortt = new Sort();
        sortt.setSort(field);

        Directory d=null;
        DirectoryReader open=null;
        try {
             d = FSDirectory.open(new File(indexPath));
             open = DirectoryReader.open(d);


            IndexSearcher indexSearcher = new IndexSearcher(open);
            ScoreDoc lastSd = getLastScoreDoc(pageQuery.getPageNum(), pageQuery.getPageSize(), booleanQuery, indexSearcher, sortt);
            //通过最后一个元素搜索下一页的pageSize元素
            TopDocs result = indexSearcher.searchAfter(lastSd, booleanQuery, pageQuery.getPageSize(), sortt);

//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
//        TopDocs topDocs = indexSearcher.search(booleanQuery, 0);
            System.out.println("总共有【" + result.totalHits + "】条匹配的结果。");
            int hits = result.totalHits;
            pageResult.setTotal(hits);
            ArrayList<DaxxWs> daxxWsList = new ArrayList<>();
            for (ScoreDoc scoreDoc : result.scoreDocs) {
                int doc = scoreDoc.doc;
                DaxxWs daxxWs = new DaxxWs();
                Document document = indexSearcher.doc(doc);
                setEntity(document, daxxWs);
                daxxWsList.add(daxxWs);
            }
            ArrayList<DamlWsVo> damlWsVos = new ArrayList<>();
            for (DaxxWs record : daxxWsList) {
                //自编号 -》文件编号
                damlWsVos.add(new DamlWsVo(record.getId(), record.getId() + "", record.getDabh(), record.getTypeId(), record.getTypeName(), record.getWjmc(), record.getWh(), record.getDwmc()));
            }
            pageResult.setData(damlWsVos);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void searchGryfPageMl(Integer typeId, String keyword, Integer startyear, Integer stopyear, PageQuery pageQuery, String sort, PageResult pageResult, String year) throws org.apache.lucene.queryparser.classic.ParseException {


        //模糊参数
        List<String> list = getGryfCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        BooleanQuery booleanQuery = new BooleanQuery();
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }
        //全等查询
        TermQuery termQuery = new TermQuery(new Term("grtypeId", typeId + ""));
        TermQuery termQuery2 = new TermQuery(new Term("gryear", year + ""));
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("gryear", startyear, stopyear, true, true);
//        BytesRef min = new BytesRef((startyear+"").getBytes());
//        BytesRef max = new BytesRef((stopyear+"").getBytes());
//        TermRangeQuery year = new TermRangeQuery("gryear", min, max, true, true);
        // 多条件必备神器
        booleanQuery.add(termQuery2, BooleanClause.Occur.MUST);
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);

//        设置排序 SortField 1排序字段 2字段类型 3true 降序 false升序
        SortField field = null;
        if (sort.equalsIgnoreCase("desc")) {
            field = new SortField("grid", SortField.Type.INT, true);
        } else {
            field = new SortField("grid", SortField.Type.INT, false);
        }

        Sort sortt = new Sort();
        sortt.setSort(field);
        Directory d=null;
        DirectoryReader open=null;

        try {
             d = FSDirectory.open(new File(indexPath));
             open = DirectoryReader.open(d);


            IndexSearcher indexSearcher = new IndexSearcher(open);
            ScoreDoc lastSd = getLastScoreDoc(pageQuery.getPageNum(), pageQuery.getPageSize(), booleanQuery, indexSearcher, sortt);
            //通过最后一个元素搜索下一页的pageSize元素
            TopDocs result = indexSearcher.searchAfter(lastSd, booleanQuery, pageQuery.getPageSize(), sortt);

//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
//        TopDocs topDocs = indexSearcher.search(booleanQuery, 0);
            System.out.println("总共有【" + result.totalHits + "】条匹配的结果。");
            int hits = result.totalHits;
            pageResult.setTotal(hits);
            ArrayList<GryfKj> gryfKjArrayList = new ArrayList<>();
            for (ScoreDoc scoreDoc : result.scoreDocs) {
                int doc = scoreDoc.doc;
                GryfKj gryfKj = new GryfKj();
                Document document = indexSearcher.doc(doc);
                setEntity(document, gryfKj);
                gryfKjArrayList.add(gryfKj);
            }
            ArrayList<DajsKjGryfVo> dajsKjGryfVos = new ArrayList<>();
            for (GryfKj gryfKj : gryfKjArrayList) {
                dajsKjGryfVos.add(new DajsKjGryfVo(gryfKj.getId(), gryfKj.getDabh(), gryfKj.getTownBsc(), gryfKj.getVillageJwh(), gryfKj.getSqr(), gryfKj.getSqcl()));
            }
            pageResult.setData(dajsKjGryfVos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public void searchGryfPage(Integer typeId, String keyword, Integer startyear, Integer stopyear, PageQuery pageQuery, String sort, PageResult pageResult) throws org.apache.lucene.queryparser.classic.ParseException {


        //模糊参数
        List<String> list = getGryfCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        BooleanQuery booleanQuery = new BooleanQuery();
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }
        //全等查询
        TermQuery termQuery = new TermQuery(new Term("grtypeId", typeId + ""));
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("gryear", startyear, stopyear, true, true);
        if (startyear != null && stopyear != null) {
            BytesRef min = new BytesRef((startyear + "").getBytes());
            BytesRef max = new BytesRef((stopyear + "").getBytes());
            TermRangeQuery year = new TermRangeQuery("gryear", min, max, true, true);
            booleanQuery.add(year, BooleanClause.Occur.MUST);
        }
        // 多条件必备神器


//        设置排序 SortField 1排序字段 2字段类型 3true 降序 false升序
        SortField field = null;
        if (sort.equalsIgnoreCase("desc")) {
            field = new SortField("grid", SortField.Type.INT, true);
        } else {
            field = new SortField("grid", SortField.Type.INT, false);
        }

        Sort sortt = new Sort();
        sortt.setSort(field);

        Directory d=null;
        DirectoryReader open=null;

        try {
             d = FSDirectory.open(new File(indexPath));
             open = DirectoryReader.open(d);


            IndexSearcher indexSearcher = new IndexSearcher(open);
            ScoreDoc lastSd = getLastScoreDoc(pageQuery.getPageNum(), pageQuery.getPageSize(), booleanQuery, indexSearcher, sortt);
            //通过最后一个元素搜索下一页的pageSize元素
            TopDocs result = indexSearcher.searchAfter(lastSd, booleanQuery, pageQuery.getPageSize(), sortt);

//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
//        TopDocs topDocs = indexSearcher.search(booleanQuery, 0);
            System.out.println("总共有【" + result.totalHits + "】条匹配的结果。");
            int hits = result.totalHits;
            pageResult.setTotal(hits);
            ArrayList<GryfKj> gryfKjArrayList = new ArrayList<>();
            for (ScoreDoc scoreDoc : result.scoreDocs) {
                int doc = scoreDoc.doc;
                GryfKj gryfKj = new GryfKj();
                Document document = indexSearcher.doc(doc);
                setEntity(document, gryfKj);
                gryfKjArrayList.add(gryfKj);
            }
            ArrayList<DajsKjGryfVo> dajsKjGryfVos = new ArrayList<>();
            for (GryfKj gryfKj : gryfKjArrayList) {
                dajsKjGryfVos.add(new DajsKjGryfVo(gryfKj.getId(), gryfKj.getDabh(), gryfKj.getTownBsc(), gryfKj.getVillageJwh(), gryfKj.getSqr(), gryfKj.getSqcl()));
            }
            pageResult.setData(dajsKjGryfVos);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public ArrayList<Daxx> searchDaxx(Integer typeId, String keyword, Integer startyear, Integer stopyear, String sort) throws org.apache.lucene.queryparser.classic.ParseException {

        //模糊参数
        List<String> list = getKjCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        BooleanQuery booleanQuery = new BooleanQuery();
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }


        //全等查询
        TermQuery termQuery = new TermQuery(new Term("kjtypeId", typeId + ""));
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等


//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("kjyear", startyear, stopyear, true, true);
        if (startyear != null && stopyear != null) {
            BytesRef min = new BytesRef((startyear + "").getBytes());
            BytesRef max = new BytesRef((stopyear + "").getBytes());
            TermRangeQuery year = new TermRangeQuery("kjyear", min, max, true, true);
            booleanQuery.add(year, BooleanClause.Occur.MUST);
        }

        // 多条件必备神器

//        设置排序 SortField 1排序字段 2字段类型 3true 降序 false升序
        SortField field = null;
        if (sort.equalsIgnoreCase("desc")) {
            field = new SortField("kjid", SortField.Type.INT, true);
        } else {
            field = new SortField("kjid", SortField.Type.INT, false);
        }

        Sort sortt = new Sort();
        sortt.setSort(field);

        ArrayList<Daxx> daxxes = null;
        Directory d=null;
        DirectoryReader open=null;
        try {
            d = FSDirectory.open(new File(indexPath));
            open = DirectoryReader.open(d);


            IndexSearcher indexSearcher = new IndexSearcher(open);
//        ScoreDoc lastSd = getLastScoreDoc(pageQuery.getPageNum(), pageQuery.getPageSize(), booleanQuery, indexSearcher,sortt);
            //通过最后一个元素搜索下一页的pageSize元素
//        TopDocs result = indexSearcher.searchAfter(lastSd, booleanQuery, pageQuery.getPageSize(),sortt);
            TopDocs result = indexSearcher.search(booleanQuery, 100000);
//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
//        TopDocs topDocs = indexSearcher.search(booleanQuery, 0);
            System.out.println("总共有【" + result.totalHits + "】条匹配的结果。");
            int hits = result.totalHits;
            daxxes = new ArrayList<>();
            for (ScoreDoc scoreDoc : result.scoreDocs) {
                int doc = scoreDoc.doc;
                Daxx daxx = new Daxx();
                Document document = indexSearcher.doc(doc);
                setEntity(document, daxx);
                daxxes.add(daxx);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return daxxes;
    }

    public ArrayList<DaxxWs> searchDaxxWs(Integer typeId, String keyword, Integer startyear, Integer stopyear, String sort) throws org.apache.lucene.queryparser.classic.ParseException {

        //模糊参数
        List<String> list = getWsCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        BooleanQuery booleanQuery = new BooleanQuery();
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }
        //全等查询
        TermQuery termQuery = new TermQuery(new Term("wstypeId", typeId + ""));
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("wsyear", startyear, stopyear, true, true);
        if (startyear != null && stopyear != null) {
            BytesRef min = new BytesRef((startyear + "").getBytes());
            BytesRef max = new BytesRef((stopyear + "").getBytes());
            TermRangeQuery year = new TermRangeQuery("wsnf", min, max, true, true);
            booleanQuery.add(year, BooleanClause.Occur.MUST);
        }
        // 多条件必备神器


//        设置排序 SortField 1排序字段 2字段类型 3true 降序 false升序
        SortField field = null;
        if (sort.equalsIgnoreCase("desc")) {
            field = new SortField("wsid", SortField.Type.INT, true);
        } else {
            field = new SortField("wsid", SortField.Type.INT, false);
        }

        Sort sortt = new Sort();
        sortt.setSort(field);

        Directory d = null;
        DirectoryReader open = null;
        ArrayList<DaxxWs> daxxWsList = null;
        try {
            d = FSDirectory.open(new File(indexPath));
            open = DirectoryReader.open(d);


            IndexSearcher indexSearcher = new IndexSearcher(open);
//        ScoreDoc lastSd = getLastScoreDoc(pageQuery.getPageNum(), pageQuery.getPageSize(), booleanQuery, indexSearcher,sortt);
            //通过最后一个元素搜索下一页的pageSize元素
//        TopDocs result = indexSearcher.searchAfter(lastSd, booleanQuery, pageQuery.getPageSize(),sortt);
            TopDocs result = indexSearcher.search(booleanQuery, 100000);
//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
//        TopDocs topDocs = indexSearcher.search(booleanQuery, 0);
            System.out.println("总共有【" + result.totalHits + "】条匹配的结果。");
            int hits = result.totalHits;
            daxxWsList = new ArrayList<>();
            for (ScoreDoc scoreDoc : result.scoreDocs) {
                int doc = scoreDoc.doc;
                DaxxWs daxxWs = new DaxxWs();
                Document document = indexSearcher.doc(doc);
                setEntity(document, daxxWs);
                daxxWsList.add(daxxWs);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return daxxWsList;
    }

    public ArrayList<GryfKj> searchGryf(Integer typeId, String keyword, Integer startyear, Integer stopyear, String sort) throws org.apache.lucene.queryparser.classic.ParseException {

        //模糊参数
        List<String> list = getGryfCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        BooleanQuery booleanQuery = new BooleanQuery();
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }
        //全等查询
        TermQuery termQuery = new TermQuery(new Term("grtypeId", typeId + ""));
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("gryear", startyear, stopyear, true, true);
        if (startyear != null && stopyear != null) {
            BytesRef min = new BytesRef((startyear + "").getBytes());
            BytesRef max = new BytesRef((stopyear + "").getBytes());
            TermRangeQuery year = new TermRangeQuery("gryear", min, max, true, true);
            booleanQuery.add(year, BooleanClause.Occur.MUST);
        }
        // 多条件必备神器
//        设置排序 SortField 1排序字段 2字段类型 3true 降序 false升序
        SortField field = null;
        if (sort.equalsIgnoreCase("desc")) {
            field = new SortField("grid", SortField.Type.INT, true);
        } else {
            field = new SortField("grid", SortField.Type.INT, false);
        }
        Sort sortt = new Sort();
        sortt.setSort(field);

        ArrayList<GryfKj> gryfKjArrayList = null;
        Directory d = null;
        DirectoryReader open = null;
        try {
             d = FSDirectory.open(new File(indexPath));
             open = DirectoryReader.open(d);


            IndexSearcher indexSearcher = new IndexSearcher(open);
            //通过最后一个元素搜索下一页的pageSize元素
            TopDocs result = indexSearcher.search(booleanQuery, 100000);
//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
//        TopDocs topDocs = indexSearcher.search(booleanQuery, 0);
            System.out.println("总共有【" + result.totalHits + "】条匹配的结果。");
            int hits = result.totalHits;
            gryfKjArrayList = new ArrayList<>();
            for (ScoreDoc scoreDoc : result.scoreDocs) {
                int doc = scoreDoc.doc;
                GryfKj gryfKj = new GryfKj();
                Document document = indexSearcher.doc(doc);
                setEntity(document, gryfKj);
                gryfKjArrayList.add(gryfKj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return gryfKjArrayList;
    }

    public void searchClxx(ArrayList<Integer> typeIds, String keyword, String sort, PageResult pageResult, PageQuery pageQuery) throws org.apache.lucene.queryparser.classic.ParseException {

        //模糊参数
        List<String> list = getClxxCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        BooleanQuery booleanQuery = new BooleanQuery();
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }

        if (typeIds.size() > 0) {
            QueryParser parser = new QueryParser("clxxtypeId", new StandardAnalyzer());
            String parmInt = getInParmInt("clxx", "typeId", typeIds);
            Query query = parser.parse(parmInt);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("gryear", startyear, stopyear, true, true);

        // 多条件必备神器


//        设置排序 SortField 1排序字段 2字段类型 3true 降序 false升序
        SortField field = null;
        if (sort.equalsIgnoreCase("desc")) {
            field = new SortField("clxxid", SortField.Type.INT, true);
        } else {
            field = new SortField("clxxid", SortField.Type.INT, false);
        }

        Sort sortt = new Sort();
        sortt.setSort(field);
        Directory d = null;
        DirectoryReader open = null;

        ArrayList<Clxx> clxxes = null;
        try {
             d = FSDirectory.open(new File(indexPath));
             open = DirectoryReader.open(d);


            IndexSearcher indexSearcher = new IndexSearcher(open);
            //通过最后一个元素搜索下一页的pageSize元素
            ScoreDoc lastSd = getLastScoreDoc(pageQuery.getPageNum(), pageQuery.getPageSize(), booleanQuery, indexSearcher, sortt);
            //通过最后一个元素搜索下一页的pageSize元素
            TopDocs result = indexSearcher.searchAfter(lastSd, booleanQuery, pageQuery.getPageSize(), sortt);
//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
//        TopDocs topDocs = indexSearcher.search(booleanQuery, 0);
            System.out.println("总共有【" + result.totalHits + "】条匹配的结果。");
            int hits = result.totalHits;
            pageResult.setTotal(hits);
            clxxes = new ArrayList<>();
            for (ScoreDoc scoreDoc : result.scoreDocs) {
                int doc = scoreDoc.doc;
                Clxx clxx = new Clxx();
                Document document = indexSearcher.doc(doc);
                setEntity(document, clxx);
                clxxes.add(clxx);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (d!=null){
                    d.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (open!=null){
                    open.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        pageResult.setData(clxxes);
    }

    public void searchClxxDabhs(ArrayList<String> dabhs, String sort, PageResult pageResult, PageQuery pageQuery) throws Exception {

        //模糊参数
//        List<String> list = getClxxCondition();
//        String[] fields = list.toArray(new String[list.size()]);
//        QueryParser queryParser = new MultiFieldQueryParser(fields,getAnalyzerSearch());
        //模糊查询keyword
        BooleanQuery booleanQuery = new BooleanQuery();
//        if (dabhs.size()>0){
        QueryParser parser = new QueryParser("clxxdabh", new StandardAnalyzer());
        String parmString = getInParmString("clxx", "dabh", dabhs);
        Query query = parser.parse(parmString);
        booleanQuery.add(query, BooleanClause.Occur.MUST);
//        }
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("gryear", startyear, stopyear, true, true);

        // 多条件必备神器


//        设置排序 SortField 1排序字段 2字段类型 3true 降序 false升序
        SortField field = null;
        if (sort.equalsIgnoreCase("desc")) {
            field = new SortField("clxxid", SortField.Type.INT, true);
        } else {
            field = new SortField("clxxid", SortField.Type.INT, false);
        }

        Sort sortt = new Sort();
        sortt.setSort(field);

        Directory d = FSDirectory.open(new File(indexPath));
        DirectoryReader open = DirectoryReader.open(d);


        IndexSearcher indexSearcher = new IndexSearcher(open);
        //通过最后一个元素搜索下一页的pageSize元素
        ScoreDoc lastSd = getLastScoreDoc(pageQuery.getPageNum(), pageQuery.getPageSize(), booleanQuery, indexSearcher, sortt);
        //通过最后一个元素搜索下一页的pageSize元素
        TopDocs result = indexSearcher.searchAfter(lastSd, booleanQuery, pageQuery.getPageSize(), sortt);
//        Filter filter = null;
        //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
        //第一个参数为通过解析要查找字符串得到的Query
        //第二个参数是
        //第三个参数是
//        Sort sort = new Sort();
//        TopDocs topDocs = indexSearcher.search(booleanQuery, 0);
        System.out.println("总共有【" + result.totalHits + "】条匹配的结果。");
        int hits = result.totalHits;
        pageResult.setTotal(hits);
        ArrayList<Clxx> clxxes = new ArrayList<>();
        for (ScoreDoc scoreDoc : result.scoreDocs) {
            int doc = scoreDoc.doc;
            Clxx clxx = new Clxx();
            Document document = indexSearcher.doc(doc);
            setEntity(document, clxx);
            clxxes.add(clxx);
        }
        pageResult.setData(clxxes);
    }

    public String getInParmInt(String type, String key, ArrayList<Integer> values) {
        String ww = "";
        for (int i = 0; i < values.size(); i++) {
            Integer integer = values.get(i);
            if (i == 0) {
                ww += ("(" + type + key + ":" + integer + ")");
            } else {
                ww += (" (" + type + key + ":" + integer + ")");
            }
        }
        return ww;
    }

    public String getInParmString(String type, String key, ArrayList<String> values) {
        String ww = "";
        for (int i = 0; i < values.size(); i++) {
            String string = values.get(i);
            if (i == 0) {
                ww += ("(" + type + key + ":" + string + ")");
            } else {
                ww += (" (" + type + key + ":" + string + ")");
            }
        }
        return ww;
    }

    private static ScoreDoc getLastScoreDoc(int pageNum, int pageSize, Query query, IndexSearcher indexSearcher, Sort sort) throws IOException {
        if (pageNum == 1) return null;
        int num = (pageNum - 1) * pageSize;
        TopDocs tds = indexSearcher.search(query, num, sort);
        return tds.scoreDocs[num - 1];
    }

    private void setEntity(Document doc, Object o) {
        try {
            java.lang.reflect.Field[] fields = o.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                String name = fields[i].getName();
                String type = null;
                if (o.getClass().getName().equals(Daxx.class.getName())) {
                    type = "kj";
                } else if (o.getClass().getName().equals(DaxxWs.class.getName())) {
                    type = "ws";
                } else if (o.getClass().getName().equals(GryfKj.class.getName())) {
                    type = "gr";
                } else if (o.getClass().getName().equals(Clxx.class.getName())) {
                    type = "clxx";
                }
                if (doc.get(type + name) == null) {
                    continue;
                }
                setFieldValueByName(name, o, o.getClass(), doc.get(type + name));


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 调用传入的对象的set方法
     *
     * @param fieldName   属性名
     * @param obj         对象实例(XXEntity)
     * @param objectClass 类名(XXEntity.getClass())
     * @param param       设置的属性的值
     * @return
     */
    public void setFieldValueByName(String fieldName, Object obj, Class objectClass, String param) {
        try {

            Class[] parameterTypes = new Class[1];
            java.lang.reflect.Field field = objectClass.getDeclaredField(fieldName);
            parameterTypes[0] = field.getType();
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "set" + firstLetter + fieldName.substring(1);
            Method method = objectClass.getMethod(getter, parameterTypes);
            method.setAccessible(true);
            if (field.getType().equals(String.class)) {
                method.invoke(obj, param);
            } else if (field.getType().equals(Integer.class) && !param.equals("")) {
                method.invoke(obj, Integer.parseInt(param));
            } else if (field.getType().equals(Date.class) && !param.equals("")) {
                Date date = getDateString(param);
                method.invoke(obj, date);
            }

        } catch (IllegalArgumentException e) {
            e.printStackTrace(); //
        } catch (Exception e) {
            e.printStackTrace(); //
        }
    }

    /**
     * 获取指定字符串出现的次数
     *
     * @param srcText  源字符串
     * @param findText 要查找的字符串
     * @return
     */
    public static int appearNumber(String srcText, String findText) {
        int count = 0;
        Pattern p = Pattern.compile(findText);
        Matcher m = p.matcher(srcText);
        while (m.find()) {
            count++;
        }
        return count;
    }

    public void add(Object o, String entiyType, IndexWriter indexWriter) throws IOException {
//        Object d = new Date();
//        if(d instanceof  Date){
//            System.out.println(1);
//        }
        Document doc = new Document();
        List<Map<String, Object>> filedsInfo = getFiledsInfo(o);
        List<String> strings = null;
        if (entiyType.equalsIgnoreCase("ws")) {
            strings = getWsCondition();
        } else if (entiyType.equalsIgnoreCase("kj")) {
            strings = getKjCondition();
        } else if (entiyType.equalsIgnoreCase("gr")) {
            strings = getGryfCondition();
        } else if (entiyType.equalsIgnoreCase("clxx")) {
            strings = getClxxCondition();
        }


        for (Map<String, Object> stringStringMap : filedsInfo) {
            String value = null;

            String type = stringStringMap.get("type").toString();
            if (stringStringMap.get("value") != null) {
                if (type.equalsIgnoreCase(Date.class.toString())) {
                    Date value1 = (Date) stringStringMap.get("value");
                    value = getStringDate(value1);
                } else {
                    value = stringStringMap.get("value").toString();
                }
            } else {
                continue;
            }
            String name = stringStringMap.get("name").toString();
            if (strings.contains(entiyType + "id")) {
//                System.out.println(entiyType + name + ":" + true + ":" + value);
                IntField intField = new IntField(entiyType + name, Integer.parseInt(value), Field.Store.YES);
                doc.add(intField);
//                doc.add(new Field(entiyType + name, value, Field.Store.YES, Field.Index.ANALYZED));
            } else if (strings.contains(entiyType + name)) {
//                System.out.println(entiyType + name + ":" + true + ":" + value);
                doc.add(new Field(entiyType + name, value, Field.Store.YES, Field.Index.ANALYZED));
            } else {
//                System.out.println(entiyType + name + ":" + false + ":" + value);
                doc.add(new Field(entiyType + name, value, Field.Store.YES, Field.Index.NOT_ANALYZED));
            }
        }
        //把对象的属性转换为Field,1、属性名称.2、属性值.3、是否存储属性的值（YES存储、NO不存储）
        //4、NO不建立索引、ANALYZER分词后建立索引、NOT_ANALYZER不分词，把整个内容作为一个词建立索引。
        //把对象的属性转换为Field,1、属性名称.2、属性值.3、是否存储属性的值（YES存储、NO不存储）
        //4、NO不建立索引、ANALYZER分词后建立索引、NOT_ANALYZER不分词，把整个内容作为一个词建立索引。

        //创建工具对象IndexWriter
        //将Document对象添加到索引库中，Lucene会自动为它指定一个唯一的编号，用来标识这一条数据。
        indexWriter.addDocument(doc);
        //关闭IndexWriter工具对象
    }

    public Analyzer getAnalyzer() {
        Analyzer analyzer = new Analyzer() {
            @Override
            protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
                Tokenizer source = new NGramTokenizer(reader, 1, 255);
                TokenStream filter = new StopFilter(source, new CharArraySet(0, false));
                return new TokenStreamComponents(source, filter);
            }
        };
        return analyzer;
    }

    public Analyzer getAnalyzerSearch() {
        Analyzer analyzer = new KeywordAnalyzer();
        return analyzer;
    }

    public List<String> getWsCondition() {
        String str = "ws";
        String[] split = "zhh,dwmc,wjmc,sj,nf,wh".split(",");
        ArrayList<String> strings = new ArrayList<>();
        for (String s : split) {
            strings.add(str + s);
        }
        return strings;
    }

    public List<String> getKjCondition() {
        String str = "kj";
        String[] split = "xmmc,jsdw,jswz,dtslbh,year,xzxmmc,ghxmmc,gcxmmc,gcjgxmmc,jsgcsgxkzbh,sggcmc".split(",");
        ArrayList<String> strings = new ArrayList<>();
        for (String s : split) {
            strings.add(str + s);
        }
        return strings;
    }

    public List<String> getGryfCondition() {
        String gryf = "gr";
        String[] split = "year,zhh,zys,qsym,zzym,bz,sqcl,spsj,sqsx,sqr,villageJwh,town_bsc,dabh".split(",");
        ArrayList<String> strings = new ArrayList<>();
        for (String s : split) {
            strings.add(gryf + s);
        }
        return strings;
    }

    public List<String> getClxxCondition() {
        String str = "clxx";
        String[] split = "dabh,wjxh,clmc,otherZh,slsj".split(",");
        ArrayList<String> strings = new ArrayList<>();
        for (String s : split) {
            strings.add(str + s);
        }
        return strings;
    }

    private List getFiledsInfo(Object o) {
        java.lang.reflect.Field[] fields = o.getClass().getDeclaredFields();
        List list = new ArrayList();
        Map infoMap = null;
        for (int i = 0; i < fields.length; i++) {
            infoMap = new HashMap();
            infoMap.put("type", fields[i].getType().toString());
            infoMap.put("name", fields[i].getName());
            infoMap.put("value", getFieldValueByName(fields[i].getName(), o));
            list.add(infoMap);
        }
        return list;
    }

    public String getStringDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = format.format(date);
        return s;
    }

    public Date getDateString(String date) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date s = format.parse(date);
        return s;
    }

    private Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

//
//    public ArrayList<DaxxWs> searchDaxxWsAll(ArrayList<Integer> integers) throws Exception {
//        if (integers==null||integers.size()<=0){
//            return null;
//        }
//        QueryParser parser = new QueryParser("wstypeId", new StandardAnalyzer());
//        String parmInt = getInParmInt("ws", "typeId", integers);
//        Query query = parser.parse(parmInt);
//
//        Directory d = FSDirectory.open(new File(indexPath));
//        DirectoryReader open = DirectoryReader.open(d);
//        IndexSearcher indexSearcher = new IndexSearcher(open);
//        TopDocs topDocs = indexSearcher.search(query, 999999999);
//        System.out.println("总共有【" + topDocs.totalHits + "】条匹配的结果。");
//        int hits = topDocs.totalHits;
//        ArrayList<DaxxWs> daxxWsList = new ArrayList<>();
//        for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
//            int doc = scoreDoc.doc;
//            DaxxWs daxxWs = new DaxxWs();
//            Document document = indexSearcher.doc(doc);
//            setEntity(document,daxxWs);
//            daxxWsList.add(daxxWs);
//        }
//        return daxxWsList;
//    }
//    public ArrayList<Daxx> searchDaxxAll(ArrayList<Integer> integers) throws Exception {
//        if (integers==null||integers.size()<=0){
//            return null;
//        }
//
//        QueryParser parser = new QueryParser("kjtypeId", new StandardAnalyzer());
//        String parmInt = getInParmInt("kj", "typeId", integers);
//        Query query = parser.parse(parmInt);
//
//
//        Directory d = FSDirectory.open(new File(indexPath));
//        DirectoryReader open = DirectoryReader.open(d);
//        IndexSearcher indexSearcher = new IndexSearcher(open);
//        TopDocs topDocs = indexSearcher.search(query, 999999999);
//        System.out.println("总共有【" + topDocs.totalHits + "】条匹配的结果。");
//        int hits = topDocs.totalHits;
//        ArrayList<Daxx> daxxes = new ArrayList<>();
//        for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
//            int doc = scoreDoc.doc;
//            Daxx daxx = new Daxx();
//            Document document = indexSearcher.doc(doc);
//            setEntity(document,daxx);
//            daxxes.add(daxx);
//        }
//        return daxxes;
//    }
//    public ArrayList<GryfKj> searchGryfAll(ArrayList<Integer> integers) throws Exception {
//        if (integers==null||integers.size()<=0){
//            return null;
//        }
//
//        QueryParser parser = new QueryParser("grtypeId", new StandardAnalyzer());
//        String parmInt = getInParmInt("gr", "typeId", integers);
//        Query query = parser.parse(parmInt);
//
//
//
//        Directory d = FSDirectory.open(new File(indexPath));
//        DirectoryReader open = DirectoryReader.open(d);
//
//        //2、使用IndexSearcher进行查询索引表
//        //建立IndexSearcher对象,参数为索引表目录
//        IndexSearcher indexSearcher = new IndexSearcher(open);
//
////        Filter filter = null;
//        //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
//        //第一个参数为通过解析要查找字符串得到的Query
//        //第二个参数是
//        //第三个参数是
////        Sort sort = new Sort();
//        TopDocs topDocs = indexSearcher.search(query, 999999999);
//        System.out.println("总共有【" + topDocs.totalHits + "】条匹配的结果。");
//        int hits = topDocs.totalHits;
//        ArrayList<GryfKj> gryfKjArrayList = new ArrayList<>();
//        for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
//            int doc = scoreDoc.doc;
//            GryfKj gryfKj = new GryfKj();
//            Document document = indexSearcher.doc(doc);
//            setEntity(document,gryfKj);
//            gryfKjArrayList.add(gryfKj);
//        }
//        return gryfKjArrayList;
//    }
//


    public Integer searchDaxxWsNf(Integer typeId, String keyword, String year) throws org.apache.lucene.queryparser.classic.ParseException {
        BooleanQuery booleanQuery = new BooleanQuery();
        //模糊参数
        List<String> list = getWsCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }


        //全等查询
        TermQuery termQuery = new TermQuery(new Term("wstypeId", typeId + ""));
        TermQuery termQuery2 = new TermQuery(new Term("wsnf", year));
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("wsnf", startyear, stopyear, true, true);
//        BytesRef min = new BytesRef((startyear+"").getBytes());
//        BytesRef max = new BytesRef((stopyear+"").getBytes());
//        TermRangeQuery year = new TermRangeQuery("wsnf", min, max, true, true);
        // 多条件必备神器

        booleanQuery.add(termQuery2, BooleanClause.Occur.MUST);
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);


        int hits = 0;
        Directory d=null;
        DirectoryReader open=null;
        try {
             d = FSDirectory.open(new File(indexPath));
             open = DirectoryReader.open(d);

            //2、使用IndexSearcher进行查询索引表
            //建立IndexSearcher对象,参数为索引表目录
            IndexSearcher indexSearcher = new IndexSearcher(open);

//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
            TopDocs topDocs = indexSearcher.search(booleanQuery, 1);
            System.out.println("总共有【" + topDocs.totalHits + "】条匹配的结果。");
            hits = topDocs.totalHits;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (d!=null){
                try {
                    d.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (open!=null){
                try {
                    open.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return hits;
    }

    public Integer searchDaxxNf(Integer typeId, String keyword, String year) throws org.apache.lucene.queryparser.classic.ParseException {
        BooleanQuery booleanQuery = new BooleanQuery();
        //模糊参数
        List<String> list = getKjCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }


        //全等查询
        TermQuery termQuery = new TermQuery(new Term("kjtypeId", typeId + ""));
        TermQuery termQuery2 = new TermQuery(new Term("kjyear", year));
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("kjyear", startyear, stopyear, true, true);
//        BytesRef min = new BytesRef((startyear+"").getBytes());
//        BytesRef max = new BytesRef((stopyear+"").getBytes());
//        TermRangeQuery year = new TermRangeQuery("kjyear", min, max, true, true);
        // 多条件必备神器

        booleanQuery.add(termQuery2, BooleanClause.Occur.MUST);
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);


        int hits = 0;
        Directory d=null;
        DirectoryReader open=null;
        try {
             d = FSDirectory.open(new File(indexPath));
             open = DirectoryReader.open(d);

            //2、使用IndexSearcher进行查询索引表
            //建立IndexSearcher对象,参数为索引表目录
            IndexSearcher indexSearcher = new IndexSearcher(open);

//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
            TopDocs topDocs = indexSearcher.search(booleanQuery, 1);
            System.out.println("总共有【" + topDocs.totalHits + "】条匹配的结果。");
            hits = topDocs.totalHits;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (d!=null){
                try {
                    d.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (open!=null){
                try {
                    open.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return hits;
    }

    public Integer searchGryfNf(Integer typeId, String keyword, String year) throws org.apache.lucene.queryparser.classic.ParseException {
        BooleanQuery booleanQuery = new BooleanQuery();
        //模糊参数
        List<String> list = getGryfCondition();
        String[] fields = list.toArray(new String[list.size()]);
        QueryParser queryParser = new MultiFieldQueryParser(fields, getAnalyzerSearch());
        //模糊查询keyword
        if (keyword != null && !keyword.trim().equals("")) {
            Query query = queryParser.parse(keyword);
            booleanQuery.add(query, BooleanClause.Occur.MUST);
        }


        //全等查询
        TermQuery termQuery = new TermQuery(new Term("grtypeId", typeId + ""));
        TermQuery termQuery2 = new TermQuery(new Term("gryear", year));
        //范围查询 1参数名 2 start 3 stop 4是否相等 5是否相等
//        NumericRangeQuery<Integer> year = NumericRangeQuery.newIntRange("gryear", startyear, stopyear, true, true);

//        BytesRef min = new BytesRef((startyear+"").getBytes());
//        BytesRef max = new BytesRef((stopyear+"").getBytes());
//        TermRangeQuery year = new TermRangeQuery("gryear", min, max, true, true);
        // 多条件必备神器

        booleanQuery.add(termQuery2, BooleanClause.Occur.MUST);
        booleanQuery.add(termQuery, BooleanClause.Occur.MUST);

        Directory d=null;
        DirectoryReader open=null;

        int hits = 0;
        try {
             d = FSDirectory.open(new File(indexPath));
             open = DirectoryReader.open(d);

            //2、使用IndexSearcher进行查询索引表
            //建立IndexSearcher对象,参数为索引表目录
            IndexSearcher indexSearcher = new IndexSearcher(open);

//        Filter filter = null;
            //使用IndexSearcher.search()进行查询，返回TopDocs对象，是包含结果的多个信息的一个对象。
            //第一个参数为通过解析要查找字符串得到的Query
            //第二个参数是
            //第三个参数是
//        Sort sort = new Sort();
            TopDocs topDocs = indexSearcher.search(booleanQuery, 1);
            System.out.println("总共有【" + topDocs.totalHits + "】条匹配的结果。");
            hits = topDocs.totalHits;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (d!=null){
                try {
                    d.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (open!=null){
                try {
                    open.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return hits;
    }

}
